﻿using System;
using EPiBoost.Core.Helpers;
using EPiServer.Filters;
using EPiServer.Core;

namespace EPiBoost.Core.Filters.PageFilters
{ 
    
    public enum DateMode {LessThan = 0, Equal = 1, GreaterThan = 2}

    public class FilterDate : IPageFilter
    {
        public DateTime Date{ get;set;}
        public string PropertyName { get; set; }
        public DateMode DateFilterMode{get; set;}

        public FilterDate()
        {
        }

        public FilterDate(DateTime date, DateMode dateFilterMode)
        {
            this.Date = date;
            this.DateFilterMode = dateFilterMode;
        }

        public void Filter(PageDataCollection pages)
        {
            for (int i = pages.Count - 1; i >= 0; i--)
            {      
                if (DateFilterMode == DateMode.LessThan && GetDateFilterProperty(pages[i]).Date >= Date
                    || DateFilterMode == DateMode.GreaterThan && GetDateFilterProperty(pages[i]).Date <= Date
                    || DateFilterMode == DateMode.Equal && GetDateFilterProperty(pages[i]).Date != Date)
                {
                    pages.RemoveAt(i);
                }                 
            }
        }

        private DateTime GetDateFilterProperty(PageData p)
        {
            if (!String.IsNullOrEmpty(PropertyName))
            {
                DateTime? date = p.GetDateTimeProperty(PropertyName, true);
                if (date.HasValue)
                    return date.Value;
            }

            return p.Created;
        }

        public void Filter(object sender, FilterEventArgs e)
        {
            this.Filter(e.Pages);
        }

        public bool ShouldFilter(PageData page)
        {
            throw new NotImplementedException();
        }
    }
}